﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;

using iTool.SQL.Analysis.Context;
using iTool.SQL.Analysis.Context.Options;
using iTool.SQL.Analysis.Context.SQLWhereOptions;

using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;

namespace iTool.SQL.Analysis.WhereClause
{
    public class SqlExistsBooleanExpressionAnalysis : SqlAnalysisBase
    {
        public SqlExistsBooleanExpressionAnalysis(SqlAnalysisContext context) : base(context)
        {
        }

        public override void Analysis()
        {
            var groupWheres = base.GetGroupWhere();
            WhereOptions whereOptions = new WhereOptions();
            SubWhereOptions sub = null;
            whereOptions.Parent = base.WhereOptions;

            if (base.WhereOptions is GroupWhereOptions group)
            {
                group.Wheres.Add(whereOptions);
            }
            else if (base.WhereOptions is SubWhereOptions)
            {
                sub = (SubWhereOptions)base.WhereOptions;
                // sub.Wheres[^1] is group
                if (sub.Wheres.Count == 0)
                {
                    sub.Wheres.Add(new GroupWhereOptions());
                }
                sub.Wheres[^1].Wheres.Add(whereOptions);
            }
            else
            {
                groupWheres[^1].Wheres.Add(whereOptions);
            }

            whereOptions.ComparisonBooleanExpressionType = base.CodeObject.Parent is SqlNotBooleanExpression ? ComparisonBooleanExpressionType.NotExists : ComparisonBooleanExpressionType.Exists;

            //base.GetWhereBuilder().Append(" exists");
            base.Next(whereOptions: whereOptions);
        }

        public override bool Validation(SqlCodeObject codeObject) => true;
    }
}
